<script lang="ts" setup>
  import { Game, GameEnrollType, GamePlay, GamePlayResult } from '@/types/game';
  import { onMounted, ref } from 'vue';
  import {
    getAllPlayTypes,
    getGameEnrollTypes,
    getGamePlayList,
  } from '@/api/game';
  import GamePlayAdder from './game-play-adder.vue';
  import GamePlayItem from './game-play-item.vue';

  const props = defineProps<{
    gameInfo: Game;
    gameId: string;
    isParent: boolean;
  }>();

  const gamePlayTypes = ref<GamePlay[]>([]);
  const gamePlayResultList = ref<GamePlayResult[]>([]);

  const initGamePlayResultData = async () => {
    const res = await getGamePlayList(props.gameId);
    gamePlayResultList.value = res.data.data || [];
  };

  const gameEnrollTypes = ref<GameEnrollType[]>([]);

  const initGameEnrollData = async () => {
    const res = await getGameEnrollTypes(props.gameId);
    gameEnrollTypes.value = res.data.data;
  };

  onMounted(async () => {
    try {
      const res = await getAllPlayTypes();
      gamePlayTypes.value = res.data.data;

      initGameEnrollData();
      initGamePlayResultData();
    } finally {
      // do nothing
    }
  });

  const adding = ref(false);
  const handleAddDone = (refresh: boolean) => {
    adding.value = false;
    if (refresh) {
      initGamePlayResultData();
    }
  };

  const goToRank = () => {
    window.open(
      `${import.meta.env.VITE_WWW_URL}/game/rank-detail?gameId=${props.gameId}`
    );
  };
</script>

<template>
  <div>
    <a-row :gutter="[12, 12]">
      <a-col v-for="gamePlay in gamePlayResultList" :key="gamePlay.id">
        <GamePlayItem
          :game-play="gamePlay"
          :play-types="gamePlayTypes"
          :enroll-types="gameEnrollTypes"
          :with-run="gameInfo.childGameCount !== 2"
          @update="initGamePlayResultData"
        />
      </a-col>
      <a-col>
        <a-space>
          <a-button type="primary" @click="adding = true">
            <template #icon><icon-plus /></template>
            添加玩法
          </a-button>

          <a-button @click="goToRank">
            <template #icon><icon-link /></template>
            成绩链接
          </a-button>
        </a-space>
      </a-col>
    </a-row>

    <GamePlayAdder
      v-if="adding"
      :game-id="gameId"
      :is-parent="isParent"
      :game-info="gameInfo"
      @close="handleAddDone"
    />
  </div>
</template>
